import React, { useState, useEffect } from 'react';
import { StorageService } from '@/services/storage';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { ColorScheme } from '@/types';
import { formatDate } from '@/utils';

export const HistoryPage: React.FC = () => {
  const [schemes, setSchemes] = useState<ColorScheme[]>([]);
  const [filteredSchemes, setFilteredSchemes] = useState<ColorScheme[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState<string>('all');
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [schemeToDelete, setSchemeToDelete] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const schemeTypes = [
    { value: 'all', label: '全部类型' },
    { value: 'complementary', label: '互补色' },
    { value: 'analogous', label: '类似色' },
    { value: 'triadic', label: '三角色' },
    { value: 'tetradic', label: '四角色' },
    { value: 'monochromatic', label: '单色调' },
    { value: 'custom', label: '自定义' }
  ];

  useEffect(() => {
    loadSchemes();
  }, []);

  useEffect(() => {
    filterSchemes();
  }, [schemes, searchQuery, selectedType, showFavoritesOnly]);

  const loadSchemes = async () => {
    try {
      setIsLoading(true);
      const data = await StorageService.getColorSchemes();
      setSchemes(data.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()));
    } catch (error) {
      console.error('Failed to load schemes:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const filterSchemes = () => {
    let filtered = schemes;

    // 按搜索查询过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(scheme =>
        scheme.name.toLowerCase().includes(query) ||
        scheme.description?.toLowerCase().includes(query) ||
        scheme.tags.some(tag => tag.toLowerCase().includes(query))
      );
    }

    // 按类型过滤
    if (selectedType !== 'all') {
      filtered = filtered.filter(scheme => scheme.type === selectedType);
    }

    // 按收藏状态过滤
    if (showFavoritesOnly) {
      filtered = filtered.filter(scheme => scheme.isFavorite);
    }

    setFilteredSchemes(filtered);
  };

  const handleToggleFavorite = async (id: string) => {
    try {
      await StorageService.toggleFavorite(id);
      await loadSchemes();
    } catch (error) {
      alert('操作失败');
    }
  };

  const handleDeleteScheme = async () => {
    if (!schemeToDelete) return;

    try {
      await StorageService.deleteColorScheme(schemeToDelete);
      await loadSchemes();
      setShowDeleteModal(false);
      setSchemeToDelete(null);
    } catch (error) {
      alert('删除失败');
    }
  };

  const handleExportScheme = (scheme: ColorScheme) => {
    const exportData = {
      name: scheme.name,
      type: scheme.type,
      colors: scheme.colors.map(color => ({
        hex: color.hex,
        rgb: color.rgb,
        hsl: color.hsl,
        name: color.name
      })),
      createdAt: scheme.createdAt,
      tags: scheme.tags
    };

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${scheme.name}-${scheme.id}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">搭配历史</h1>
        <p className="text-gray-600">查看和管理你保存的色彩搭配方案</p>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow-md p-4">
          <div className="text-2xl font-bold text-blue-600">{schemes.length}</div>
          <div className="text-sm text-gray-600">总方案数</div>
        </div>
        <div className="bg-white rounded-lg shadow-md p-4">
          <div className="text-2xl font-bold text-green-600">
            {schemes.filter(s => s.isFavorite).length}
          </div>
          <div className="text-sm text-gray-600">收藏方案</div>
        </div>
        <div className="bg-white rounded-lg shadow-md p-4">
          <div className="text-2xl font-bold text-purple-600">
            {schemes.reduce((sum, s) => sum + s.colors.length, 0)}
          </div>
          <div className="text-sm text-gray-600">总颜色数</div>
        </div>
        <div className="bg-white rounded-lg shadow-md p-4">
          <div className="text-2xl font-bold text-orange-600">
            {new Set(schemes.flatMap(s => s.tags)).size}
          </div>
          <div className="text-sm text-gray-600">使用标签</div>
        </div>
      </div>

      {/* 筛选和搜索 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="md:col-span-2">
            <Input
              value={searchQuery}
              onChange={setSearchQuery}
              placeholder="搜索方案名称、描述或标签..."
            />
          </div>
          <div>
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
            >
              {schemeTypes.map(type => (
                <option key={type.value} value={type.value}>
                  {type.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={showFavoritesOnly}
                onChange={(e) => setShowFavoritesOnly(e.target.checked)}
                className="mr-2"
              />
              <span className="text-sm text-gray-700">仅显示收藏</span>
            </label>
          </div>
        </div>
      </div>

      {/* 方案列表 */}
      {filteredSchemes.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredSchemes.map((scheme) => (
            <div
              key={scheme.id}
              className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow"
            >
              {/* 颜色预览 */}
              <div className="h-24 flex">
                {scheme.colors.slice(0, 5).map((color, index) => (
                  <div
                    key={index}
                    className="flex-1"
                    style={{ backgroundColor: color.hex }}
                    title={color.hex}
                  />
                ))}
                {scheme.colors.length > 5 && (
                  <div className="flex-1 bg-gray-200 flex items-center justify-center">
                    <span className="text-gray-600 text-sm">+{scheme.colors.length - 5}</span>
                  </div>
                )}
              </div>

              {/* 方案信息 */}
              <div className="p-4">
                <div className="flex items-start justify-between mb-2">
                  <h3 className="text-lg font-semibold text-gray-900 truncate">
                    {scheme.name}
                  </h3>
                  <button
                    onClick={() => handleToggleFavorite(scheme.id)}
                    className={`ml-2 ${scheme.isFavorite ? 'text-red-500' : 'text-gray-400'} hover:text-red-600`}
                  >
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" clipRule="evenodd" />
                    </svg>
                  </button>
                </div>

                {scheme.description && (
                  <p className="text-sm text-gray-600 mb-3 line-clamp-2">
                    {scheme.description}
                  </p>
                )}

                <div className="flex items-center justify-between text-sm text-gray-500 mb-3">
                  <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
                    {schemeTypes.find(t => t.value === scheme.type)?.label || scheme.type}
                  </span>
                  <span>{scheme.colors.length} 色</span>
                </div>

                {scheme.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1 mb-3">
                    {scheme.tags.slice(0, 3).map((tag, index) => (
                      <span
                        key={index}
                        className="bg-gray-100 text-gray-700 px-2 py-1 rounded text-xs"
                      >
                        {tag}
                      </span>
                    ))}
                    {scheme.tags.length > 3 && (
                      <span className="text-gray-500 text-xs">+{scheme.tags.length - 3}</span>
                    )}
                  </div>
                )}

                <div className="text-xs text-gray-500 mb-3">
                  创建于 {formatDate(new Date(scheme.createdAt), 'YYYY-MM-DD')}
                </div>

                {/* 操作按钮 */}
                <div className="flex space-x-2">
                  <Button
                    size="sm"
                    variant="outline"
                    className="flex-1"
                    onClick={() => {
                      // 加载到当前调色板的逻辑
                      window.location.href = `/color-picker?load=${scheme.id}`;
                    }}
                  >
                    加载
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleExportScheme(scheme)}
                    title="导出方案"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => {
                      setSchemeToDelete(scheme.id);
                      setShowDeleteModal(true);
                    }}
                    title="删除方案"
                    className="text-red-600 hover:text-red-700"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="bg-white rounded-lg shadow-md p-12 text-center">
          <div className="text-gray-400 mb-4">
            <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            {schemes.length === 0 ? '暂无保存的方案' : '没有符合条件的方案'}
          </h3>
          <p className="text-gray-600 mb-4">
            {schemes.length === 0 
              ? '开始创建你的第一个色彩搭配方案'
              : '尝试调整筛选条件或搜索关键词'
            }
          </p>
          {schemes.length === 0 && (
            <Button onClick={() => window.location.href = '/color-picker'}>
              创建方案
            </Button>
          )}
        </div>
      )}

      {/* 删除确认模态框 */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="确认删除"
      >
        <div className="space-y-4">
          <p className="text-gray-700">
            确定要删除这个色彩方案吗？此操作无法撤销。
          </p>
          <div className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setShowDeleteModal(false)}
            >
              取消
            </Button>
            <Button
              onClick={handleDeleteScheme}
              className="bg-red-600 hover:bg-red-700"
            >
              删除
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};